<template>
  <div class="create-task-form">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="form.taskName"
          placeholder="请输入任务名称"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="学期" prop="semester">
        <el-select v-model="form.semester" placeholder="请选择学期" style="width: 100%">
          <el-option
            v-for="semester in semesterOptions"
            :key="semester.value"
            :label="semester.label"
            :value="semester.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="算法配置" prop="algorithmConfigId">
        <el-select
          v-model="form.algorithmConfigId"
          placeholder="请选择算法配置"
          style="width: 100%"
          @change="handleConfigChange"
        >
          <el-option
            v-for="config in algorithmConfigs"
            :key="config.id"
            :label="config.configName + (config.isDefault ? ' (默认)' : '')"
            :value="config.id"
          >
            <span style="float: left">{{ config.configName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">
              {{ config.algorithmType }}
            </span>
          </el-option>
        </el-select>
      </el-form-item>
      
      <!-- 算法配置详情 -->
      <el-form-item v-if="selectedConfig" label="配置详情">
        <el-card class="config-detail">
          <div class="config-info">
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="config-item">
                  <label>算法类型：</label>
                  <span>{{ getAlgorithmTypeText(selectedConfig.algorithmType) }}</span>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="config-item">
                  <label>种群大小：</label>
                  <span>{{ selectedConfig.populationSize }}</span>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="config-item">
                  <label>最大迭代次数：</label>
                  <span>{{ selectedConfig.maxGenerations }}</span>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="config-item">
                  <label>交叉概率：</label>
                  <span>{{ selectedConfig.crossoverRate }}</span>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="config-item">
                  <label>变异概率：</label>
                  <span>{{ selectedConfig.mutationRate }}</span>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="config-item">
                  <label>精英保留比例：</label>
                  <span>{{ selectedConfig.eliteRate }}</span>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-form-item>
      
      <el-form-item label="约束条件">
        <el-card class="constraints-card">
          <div class="constraints-header">
            <h4>排课约束设置</h4>
            <p>请根据实际需求配置排课约束条件</p>
          </div>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="教师冲突检查" prop="constraints.teacherConflict">
                <el-switch
                  v-model="form.constraints.teacherConflict"
                  active-text="启用"
                  inactive-text="禁用"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="教室冲突检查" prop="constraints.classroomConflict">
                <el-switch
                  v-model="form.constraints.classroomConflict"
                  active-text="启用"
                  inactive-text="禁用"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="学生冲突检查" prop="constraints.studentConflict">
                <el-switch
                  v-model="form.constraints.studentConflict"
                  active-text="启用"
                  inactive-text="禁用"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="时间偏好优化" prop="constraints.timePreference">
                <el-switch
                  v-model="form.constraints.timePreference"
                  active-text="启用"
                  inactive-text="禁用"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="课程连续性" prop="constraints.courseContinuity">
                <el-switch
                  v-model="form.constraints.courseContinuity"
                  active-text="启用"
                  inactive-text="禁用"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="教室容量检查" prop="constraints.roomCapacity">
                <el-switch
                  v-model="form.constraints.roomCapacity"
                  active-text="启用"
                  inactive-text="禁用"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form-item>
      
      <el-form-item label="优化目标">
        <el-card class="objectives-card">
          <div class="objectives-header">
            <h4>优化目标权重</h4>
            <p>调整各项优化目标的权重，总和应为100%</p>
          </div>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="教师满意度" prop="objectives.teacherSatisfaction">
                <el-slider
                  v-model="form.objectives.teacherSatisfaction"
                  :min="0"
                  :max="100"
                  show-input
                  :format-tooltip="formatTooltip"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="教室利用率" prop="objectives.roomUtilization">
                <el-slider
                  v-model="form.objectives.roomUtilization"
                  :min="0"
                  :max="100"
                  show-input
                  :format-tooltip="formatTooltip"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="时间分布均匀性" prop="objectives.timeDistribution">
                <el-slider
                  v-model="form.objectives.timeDistribution"
                  :min="0"
                  :max="100"
                  show-input
                  :format-tooltip="formatTooltip"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="冲突最小化" prop="objectives.conflictMinimization">
                <el-slider
                  v-model="form.objectives.conflictMinimization"
                  :min="0"
                  :max="100"
                  show-input
                  :format-tooltip="formatTooltip"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <div class="weight-summary">
            <el-alert
              :title="'当前权重总和：' + totalWeight + '%'"
              :type="totalWeight === 100 ? 'success' : 'warning'"
              :description="totalWeight === 100 ? '权重配置正确' : '权重总和应为100%'"
              show-icon
              :closable="false"
            />
          </div>
        </el-card>
      </el-form-item>
      
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入任务备注信息"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    
    <div class="form-actions">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">创建任务</el-button>
    </div>
  </div>
</template>

<script>
import { addScheduleTask } from '@/api/jwgl/scheduleTask'
import { listAlgorithmConfig, getDefaultConfig } from '@/api/jwgl/algorithmConfig'

export default {
  name: 'CreateTaskForm',
  data() {
    return {
      submitting: false,
      algorithmConfigs: [],
      selectedConfig: null,
      form: {
        taskName: '',
        semester: '',
        algorithmConfigId: null,
        constraints: {
          teacherConflict: true,
          classroomConflict: true,
          studentConflict: true,
          timePreference: true,
          courseContinuity: false,
          roomCapacity: true
        },
        objectives: {
          teacherSatisfaction: 30,
          roomUtilization: 25,
          timeDistribution: 25,
          conflictMinimization: 20
        },
        remark: ''
      },
      rules: {
        taskName: [
          { required: true, message: '请输入任务名称', trigger: 'blur' },
          { min: 2, max: 100, message: '任务名称长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        semester: [
          { required: true, message: '请选择学期', trigger: 'change' }
        ],
        algorithmConfigId: [
          { required: true, message: '请选择算法配置', trigger: 'change' }
        ]
      },
      semesterOptions: [
        { label: '2024-2025学年第一学期', value: '2024-2025-1' },
        { label: '2024-2025学年第二学期', value: '2024-2025-2' },
        { label: '2025-2026学年第一学期', value: '2025-2026-1' },
        { label: '2025-2026学年第二学期', value: '2025-2026-2' }
      ]
    }
  },
  computed: {
    totalWeight() {
      return this.form.objectives.teacherSatisfaction +
             this.form.objectives.roomUtilization +
             this.form.objectives.timeDistribution +
             this.form.objectives.conflictMinimization
    }
  },
  watch: {
    // 监听权重变化，自动调整
    'form.objectives': {
      handler(newVal) {
        // 可以在这里添加权重自动调整逻辑
      },
      deep: true
    }
  },
  created() {
    this.loadAlgorithmConfigs()
  },
  methods: {
    /** 加载算法配置列表 */
    async loadAlgorithmConfigs() {
      try {
        const response = await listAlgorithmConfig({ status: '0' })
        this.algorithmConfigs = response.rows || []
        
        // 自动选择默认配置
        const defaultConfig = this.algorithmConfigs.find(config => config.isDefault)
        if (defaultConfig) {
          this.form.algorithmConfigId = defaultConfig.id
          this.selectedConfig = defaultConfig
        }
      } catch (error) {
        this.$modal.msgError('加载算法配置失败')
      }
    },
    
    /** 算法配置变化处理 */
    handleConfigChange(configId) {
      this.selectedConfig = this.algorithmConfigs.find(config => config.id === configId)
    },
    
    /** 格式化滑块提示 */
    formatTooltip(val) {
      return val + '%'
    },
    
    /** 获取算法类型文本 */
    getAlgorithmTypeText(type) {
      const typeMap = {
        'GENETIC': '遗传算法',
        'SIMULATED_ANNEALING': '模拟退火',
        'PARTICLE_SWARM': '粒子群优化',
        'TABU_SEARCH': '禁忌搜索'
      }
      return typeMap[type] || type
    },
    
    /** 提交表单 */
    handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (!valid) {
          return false
        }
        
        // 检查权重总和
        if (this.totalWeight !== 100) {
          this.$modal.msgWarning('优化目标权重总和必须为100%')
          return false
        }
        
        this.submitting = true
        
        try {
          // 构建配置数据
          const configData = {
            algorithmConfigId: this.form.algorithmConfigId,
            constraints: this.form.constraints,
            objectives: this.form.objectives
          }
          
          const taskData = {
            taskName: this.form.taskName,
            semester: this.form.semester,
            configData: JSON.stringify(configData),
            remark: this.form.remark
          }
          
          await addScheduleTask(taskData)
          this.$modal.msgSuccess('任务创建成功')
          this.$emit('success')
        } catch (error) {
          this.$modal.msgError('任务创建失败：' + (error.msg || error.message))
        } finally {
          this.submitting = false
        }
      })
    },
    
    /** 取消操作 */
    handleCancel() {
      this.$emit('cancel')
    }
  }
}
</script>

<style lang="scss" scoped>
.create-task-form {
  .config-detail {
    background-color: #f8f9fa;
    
    .config-info {
      .config-item {
        margin-bottom: 8px;
        
        label {
          font-weight: 500;
          color: #606266;
          margin-right: 8px;
        }
        
        span {
          color: #303133;
        }
      }
    }
  }
  
  .constraints-card,
  .objectives-card {
    .constraints-header,
    .objectives-header {
      margin-bottom: 20px;
      
      h4 {
        margin: 0 0 8px 0;
        color: #303133;
        font-size: 16px;
        font-weight: 500;
      }
      
      p {
        margin: 0;
        color: #909399;
        font-size: 13px;
      }
    }
  }
  
  .weight-summary {
    margin-top: 20px;
  }
  
  .form-actions {
    margin-top: 30px;
    text-align: right;
    border-top: 1px solid #e4e7ed;
    padding-top: 20px;
    
    .el-button {
      margin-left: 10px;
    }
  }
}

::v-deep .el-form-item__label {
  font-weight: 500;
}

::v-deep .el-card__body {
  padding: 16px;
}
</style>